package me.keiwu.task.job;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import me.keiwu.pub.data.ConfigType;
import me.keiwu.pub.data.ResponseV2;
import me.keiwu.pub.data.config.RankRateConfigBean;
import me.keiwu.pub.data.service.UserInfoBean;
import me.keiwu.pub.data.service.UserStatisticsBean;
import me.keiwu.pub.service.WXService;
import me.keiwu.pub.util.CacheUtil;
import me.keiwu.pub.util.DateUtil;
import me.keiwu.task.domain.Challenge;
import me.keiwu.task.rpc.NoticeRpc;
import me.keiwu.task.rpc.UserRpc;
import me.keiwu.task.rpc.UserStatisticsRpc;
import me.keiwu.task.service.ChallengeService;
import me.keiwu.task.util.ExceptionUtil;
import me.keiwu.task.util.bean.Achievement;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.http.HttpStatus;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by kei on 07/02/2018.
 */
@Component
public class RankJob {

    private static final Logger logger = LoggerFactory.getLogger(RankJob.class);

    @Autowired
    private CacheUtil cacheUtil;

    @Autowired
    private UserRpc userRpc;
    @Autowired
    private ChallengeService challengeService;
    @Autowired
    private UserStatisticsRpc userStatisticsRpc;
    @Autowired
    private WXService wxService;
    @Autowired
    private NoticeRpc noticeRpc;
    @Autowired
    private ExceptionUtil exceptionUtil;


    @Scheduled(cron = "0 30 22 * * ?")
    public void calcRank() {
        logger.info("RankJob calcRank...");
        int page = 0;
        int size = 100;
        cacheUtil.clearRank();
        RankRateConfigBean config = cacheUtil.getConfig(ConfigType.RANK_RATE_CONFIG, RankRateConfigBean.class);
        while (true) {
            JSONObject data = JSON.parseObject(userRpc.historyLoginUser(null, page, size));
            List list = data.getJSONArray("content");
            for (Object obj : list) {
                try {
                    JSONObject json = (JSONObject) obj;
                    Long userId = json.getLong("id");
                    UserInfoBean info = JSON.parseObject(userRpc.userInfo(userId), UserInfoBean.class);
                    double score = this.calculator(info, config);
                    cacheUtil.addRankMember(info.getId() + "", score);
                } catch (Exception e) {
                    logger.error("RankJob calculator error", e);
                }
            }
            Integer totalPages = data.getInteger("totalPages");
            logger.info("RankJob loop page={}, size={}, totalPages={}, listSize={}", page, size, totalPages, list.size());
            if (totalPages < ++page) break;
        }
    }

    private double calculator(UserInfoBean info, RankRateConfigBean config) {
        int activity = 0;
        if (DateUtil.isSameDay(new Date(), new Date(info.getLastModifiedTime()))) {
            activity = 1;
        }
        int max = config.getMaxStep() <= 0 ? 1000 : config.getMaxStep();
        int step = info.getStep() > max ? max : info.getStep();
        int gold = info.getGold();
        int level = info.getLevel();
        int challengeCnt = challengeService.countAllChallenges(info.getId());
        int startingCnt = challengeService.countStartingChallenges(info.getId());
        Achievement achievement = challengeService.getAchievement(info.getId());
        double winRate = achievement.getRate();

        UserStatisticsBean bean = JSON.parseObject(userStatisticsRpc.getUserStatistics(info.getId()), UserStatisticsBean.class);
        int explore = bean.getCommentCount() + bean.getStealGoldCount();


        double score = config.calcResult(activity, step, gold, level, challengeCnt, startingCnt, winRate, explore);

        logger.info("RankJob calculator userId={}, activity={}, step={}, gold={}, level={}, challengeCnt={}, " +
                        "startingCnt={}, winRate={}, explore={}, conf={}, score={}", info.getId(), activity, step, gold, level,
                challengeCnt, startingCnt, winRate, explore, JSON.toJSONString(config), score);
        return score;
    }

    /**
     *
     * 9.30发送比赛结果推送
     *
     */
//    @Scheduled(cron = "0 30 09 * * ?")
//    public void challengeResultNoticeJob() {
//        int page = 0;
//        int size = 100;
//        while (true) {
//            Page<Challenge> yesterdayChallenges = challengeService.findYesterdayChallenge(page, size);
//            if (yesterdayChallenges != null && yesterdayChallenges.getTotalElements() > 0) {
//                for (Challenge challenge : yesterdayChallenges) {
//                    Long initiator = challenge.getInitiator();
//                    Long challenger = challenge.getChallenger();
//                    int initiatorStep = challenge.getInitiatorStep();
//                    int challengerStep = challenge.getChallengerStep();
//
//                    if (cacheUtil.canTemplateMsgForResult(challenger)) {
//                        if (!cacheUtil.isAwardChallenge(challenger,challenge.getId())){
//                            if (sendResultTemplateMsg(initiator,challenger,initiatorStep, challengerStep, true)) {
//                                cacheUtil.recordTemplateMsgForResult(challenger);
//                            }
//                        }
//                    }
//
//                    if (cacheUtil.canTemplateMsgForResult(initiator)) {
//                        if (!cacheUtil.isAwardChallenge(initiator, challenge.getId())){
//                            if (sendResultTemplateMsg(challenger,initiator,challengerStep, initiatorStep,false)) {
//                                cacheUtil.recordTemplateMsgForResult(initiator);
//                            }
//                        }
//                    }
//
//                }
//                if (yesterdayChallenges.getTotalPages() < ++page) break;
//            }else {
//                exceptionUtil.logError(this.getClass(), "sendResultTemplateMsg", "challengeResultNoticeJob no element");
//                break;
//            }
//        }
//    }
//
//    private boolean sendResultTemplateMsg(Long fromUserId, Long toUserId, Integer fromStep, Integer toStep, boolean toIsChallenger) {
//        String fromUser = userRpc.userInfo(fromUserId);
//        UserInfoBean fromBean = JSONObject.parseObject(fromUser,UserInfoBean.class);
//        String toUser = userRpc.userInfo(toUserId);
//        UserInfoBean toBean = JSONObject.parseObject(toUser,UserInfoBean.class);
//        String userFormStr = userRpc.getUserForm(toUserId);
//        if (StringUtils.isBlank(userFormStr)) {
//            exceptionUtil.logError(this.getClass(), "sendResultTemplateMsg", "no formid to :"+toUserId);
//            return false;
//        }
//        Map<String, Object> formMap = JSON.parseObject(userFormStr, Map.class);
//        String formId = (String)formMap.get("formId");
//        Long form_db_id = ((Number)formMap.get("id")).longValue();
//
//        String initiatorName = fromBean.getNickName();
//        String vsMsg = fromBean.getNickName() + " VS " + toBean.getNickName();
//        if (!toIsChallenger) {
//            initiatorName = toBean.getNickName();
//            vsMsg = toBean.getNickName() + " VS " + fromBean.getNickName();
//        }
//
//        Map<String, Object> map = new HashMap<String, Object>();
//        map.put("initiator",initiatorName);
//        map.put("message",vsMsg);
//        map.put("formId", formId);
//        map.put("templateMsgType",1);
//        map.put("step",toStep);
//        if (Objects.equals(fromStep, toStep)) {
//            map.put("result","平局");
//            map.put("remark","马上点击查看比赛结果");
//
//        } else if (toStep > fromStep) {
//            map.put("result","胜利");
//            map.put("remark","马上点击领取奖励");
//        } else {
//            map.put("result","不幸落马");
//            map.put("remark","马上点击查看比赛结果");
//        }
//        String page = "pages/score/score";
//        // 调用发送模板 传参发送消息
//        // 0 表示CHALLENGE_CREATED 比赛结果通知
//        exceptionUtil.logError(this.getClass(), "sendResultTemplateMsg", "params:" + map.toString());
//        exceptionUtil.logError(this.getClass(), "sendResultTemplateMsg", "page:" + page);
//
//        ResponseV2 resp = wxService.sendTemplateMsg(fromUser, toUser, page, map);
//        if(resp.getCode() == HttpStatus.OK.value()) {
//            userRpc.deleteUsedForm(form_db_id);
//            return true;
//
//        }else {
//            exceptionUtil.logError(this.getClass(), "sendResultTemplateMsg", resp.getMsg());
//
//        }
//        return false;
//    }

    public static void main(String[] args) {
        System.out.println(DateUtil.getUnixTime());
        System.out.println(new Date(1517974503*1000L).toString());
    }

}
